from common_import import *


def check1(data):
    result = []
    dates = np.unique(data["销售日期"])

    # 遍历每个日期
    for date in dates:
        # 获取同一天的数据
        day_data = data[data["销售日期"] == date]

        # 检查同一商品在同一天的不同单价情况
        unique_products = np.unique(day_data["单品编码"])
        for product in unique_products:
            product_data = day_data[day_data["单品编码"] == product]
            unique_prices = np.unique(product_data["销售单价(元/千克)"])

            # 如果同一商品有不同单价，打印日期
            if len(unique_prices) > 6:
                print(f"日期 {date} 存在{product}同一商品单价不同的情况")
                print(unique_prices)


def cal_discount(data):
    total_discount = 0
    discount_count = 0

    dates = np.unique(data["销售日期"])

    # 遍历每个日期
    for date in dates:
        # 获取同一天的数据
        day_data = data[data["销售日期"] == date]

        # 检查同一商品在同一天的不同单价情况
        unique_products = np.unique(day_data["单品编码"])
        for product in unique_products:
            product_data = day_data[day_data["单品编码"] == product]
            unique_prices = np.unique(product_data["销售单价(元/千克)"])

            # 如果同一商品有不同单价，计算折扣
            if len(unique_prices) > 1:
                max_price = np.max(unique_prices)  # 原价
                discount_prices = unique_prices[unique_prices < max_price]  # 折扣价
                average_discount_for_product = np.mean(
                    (max_price - discount_prices) / max_price
                )

                # 累加折扣并计数
                total_discount += average_discount_for_product
                discount_count += 1

    # 计算并返回总体的平均折扣百分比
    if discount_count > 0:
        overall_average_discount = (total_discount / discount_count) * 100
        return round(overall_average_discount, 2)
    else:
        return 0.0  # 如果没有折扣数据，返回0


def check2(data):
    data["是否打折销售"]
    print(len(data[data["是否打折销售"] == "是"]))


def calculate_discounted_ratio(data):
    # 定义数据类型
    dtype = [("category", "i4"), ("discounted_ratio", "f4")]

    # 获取所有大类别
    categories = np.unique([mapping.get_type(code) for code in data["code"]])

    # 初始化结果数组
    results = np.zeros(len(categories), dtype=dtype)

    for i, category in enumerate(categories):
        # 获取当前大类别下的所有商品
        subset = data[[mapping.get_type(code) == category for code in data["code"]]]

        # 计算总销量和打折销量
        total_quantity = np.sum(subset["quantity"])
        discounted_quantity = np.sum(subset["quantity"][subset["discounted"] == 1])

        # 计算占比
        discounted_ratio = (
            discounted_quantity / total_quantity if total_quantity > 0 else 0
        )

        # 填充结果
        results[i] = (category, discounted_ratio)

    return results


if __name__ == "__main__":
    data = tool.get_np("2x.csv")
    result = calculate_discounted_ratio(data)
    print(result)
